package com.hmkj.web.controller.pay;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.pay.PayResult;
import com.hmkj.core.po.amount.Recharge;
import com.hmkj.core.service.amount.CashService;
import com.hmkj.core.service.amount.RechargeService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(description = "易通金服支付通道")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/pay/etone")
public class EtonePayController extends GenericController<Integer, Recharge> {


    @Autowired
    RechargeService rechargeService;

    @Autowired
    CashService cashService;

    @Autowired
    UserService userService;

    @ApiOperation(value = "调起易通支付收银台", notes = "调起易通支付收银台")
    @ResponseBody
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public ResultEntity pay(@ApiParam("充值金额") @RequestParam String amount) {
        Map<String, String> params = new HashMap<>();
        // 支付单标识
        String hmTk = UUID.randomUUID().toString();
        String baseUrl = getRequestUrl();
        // 商户返回地址
        String merURL = baseUrl + "/result?hm_tk=" + hmTk;
        try {
            // 获取支付链接，并跳转支付页面
            params.put("redirctUrl", rechargeService.doRechargeByEtone(amount, getLoginUser().getId(),baseUrl));
        } catch (BussinessException e) {
            log.error("易通支付收银台失败，错误消息：{}", e.getMessage());
            // 缓存回调结果
            redisService.put(CacheID.PAY_RESULT + hmTk, PayResult.failed(e.getMessage(), ""), 30 * 60);
            params.put("redirctUrl", merURL);
        } catch (Exception e) {
            log.error("易通支付收银台失败，错误消息：{}", e.getMessage());
            // 缓存回调结果
            redisService.put(CacheID.PAY_RESULT + hmTk, PayResult.failed("充值失败，系统繁忙", ""), 30 * 60);
            params.put("redirctUrl", merURL);
        }

        return ok("支付链接生成成功", params);
    }

}
